package com.rui.common.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Component
public class RedisUtil {
    @Resource
    private StringRedisTemplate redisTemplate;

    /**
     * Set
     *
     * @param key
     * @param value
     * @param expire
     */
    public void set(String key, Object value, long expire) {
        redisTemplate.opsForValue().set(key, toJson(value));
        if (expire != SysConst.REDIS_NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    /**
     * Set
     *
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        set(key, value, SysConst.REDIS_DEFAULT_EXPIRE);
    }

    /**
     * Get
     *
     * @param key
     * @param clazz
     * @param expire
     * @param <T>
     * @return
     */
    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = redisTemplate.opsForValue().get(key);
        if (expire != SysConst.REDIS_NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    /**
     * Get
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, SysConst.REDIS_NOT_EXPIRE);
    }

    /**
     * Get
     *
     * @param key
     * @param expire
     * @return
     */
    public String get(String key, long expire) {
        String value = redisTemplate.opsForValue().get(key);
        if (expire != SysConst.REDIS_NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    /**
     * Get
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return get(key, SysConst.REDIS_NOT_EXPIRE);
    }

    /**
     * Del
     *
     * @param key
     */
    public void del(String key) {
        redisTemplate.delete(key);
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return JsonUtil.toJson(object);
    }

    /**
     * JSON数据转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
        return JsonUtil.parse(json, clazz);
    }
}
